package com.ldc.framework.adapter

import android.os.Build
import android.text.Html
import androidx.core.text.HtmlCompat
import androidx.recyclerview.widget.RecyclerView
import com.ldc.commonlibs.listener.OnRowListener
import com.ldc.commonlibs.listener.OnRowListener2
import com.ldc.commonres.common.BaseRvAdapter
import com.ldc.commonres.common.BaseRvViewHolder
import com.ldc.commonres.uts.TagUts
import com.ldc.framework.R
import com.ldc.framework.model.ArticleModel

class SearchAdapter : BaseRvAdapter<ArticleModel>(R.layout.framework_layout_view_item_article) {
    private var onRowListener: OnRowListener<ArticleModel>? = null
    private var onCollectListener: OnRowListener2<ArticleModel, Int>? = null

    fun addOnRowListener(listener: OnRowListener<ArticleModel>) {
        this.onRowListener = listener
    }

    fun addCollectRowListener(listener: OnRowListener2<ArticleModel, Int>) {
        this.onCollectListener = listener
    }

    fun changeDataItem(position: Int) {
        val data = getData()[position]
        getData()[position].collect = !data.collect
        notifyItemChanged(position, getData())
    }

    override fun convertTo(holder: BaseRvViewHolder, data: ArticleModel, position: Int) {
        holder.setImage(R.id.iv_icon, data.envelopePic)
        holder.visibility(R.id.iv_icon, data.envelopePic.isNotBlank() || data.envelopePic != "")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val title: CharSequence = Html.fromHtml(data.title, HtmlCompat.FROM_HTML_MODE_COMPACT)
            val desc: CharSequence = Html.fromHtml(data.desc, HtmlCompat.FROM_HTML_MODE_COMPACT)
            holder.setText(R.id.tv_desc, desc)
            holder.setText(R.id.tv_title, title)
        } else {
            holder.setText(R.id.tv_title, data.title)
            holder.setText(R.id.tv_desc, data.desc)
        }
        holder.visibility(R.id.tv_desc, data.desc.isNotEmpty())
        holder.setText(R.id.tv_chapter_name, "${data.superChapterName}-${data.chapterName}")
        holder.setText(R.id.tv_author, data.author)
        holder.setText(R.id.tv_date, data.niceShareDate)
        holder.visibility(R.id.ll_fresh, data.fresh)
        holder.visibility(R.id.ll_zan, data.zan > 0)
        holder.setText(R.id.tv_zan, "${data.zan}")
        holder.setImage(
            R.id.iv_collect,
            if (data.collect) com.ldc.commonres.R.drawable.res_icon_collect else com.ldc.commonres.R.drawable.res_icon_un_collect
        )
        holder.setText(
            R.id.tv_collect, if (data.collect) "已收藏" else "收藏"
        )
        holder.visibility(R.id.rv_tag_list, data.tags.isNotEmpty())
        if (data.tags.isNotEmpty()) {
            TagUts.tagList(data.tags, holder.findView(R.id.rv_tag_list) as RecyclerView)
        }
        // 设置点击事件
        holder.addOnRowListener(holder.itemView, data, onRowListener)
        holder.addOnRowListener2(R.id.ll_collect, data, position, onCollectListener)

    }
}